package com.sdkx.wear_os.viewmodel

import android.annotation.SuppressLint
import android.app.Application
import android.app.Dialog
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.MediaStore.Downloads
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.TextView
import com.daimajia.numberprogressbar.NumberProgressBar
import com.lihang.ShadowLayout
import com.sdkx.wear_os.R
import com.sdkx.wear_os.app.MyApplication
import com.sdkx.wear_os.base.BaseViewModel
import com.sdkx.wear_os.customview.customizeDialogCenter
import com.sdkx.wear_os.retrofit.download.DownloadStatus
import com.sdkx.wear_os.retrofit.download.IDownloadBuild
import com.sdkx.wear_os.utils.ToastLogUtils.logUtil
import com.sdkx.wear_os.utils.dateToString
import com.sdkx.wear_os.utils.getAppName
import com.sdkx.wear_os.utils.savePath
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableSharedFlow
import java.io.File
import java.util.*
import kotlin.math.floor
import kotlin.system.exitProcess


/**
 * 下载文件viewModel
 */
@SuppressLint("StaticFieldLeak")
class DownLoadViewModel(
    application: Application
) : BaseViewModel(application), View.OnClickListener {
    var context: Context? = null

    private var progressBar: NumberProgressBar? = null
    private var updateSure: ShadowLayout? = null
    private var updateCancel: TextView? = null
    private var downloadDialog: Dialog? = null

    //下载完成
    var downloadSuccessFlow: MutableSharedFlow<Uri?>? = null

    //下载地址
    private lateinit var url: String

    //是否强制
    private var forceReplace: Boolean = false

    //协程
    private var job: Job? = null

    /**
     * 升级弹窗
     * @param content 内容
     * @param url 地址
     * @param forceReplace 是否强制
     */
    fun updateDialog(
        context: Context,
        content: String,
        url: String,
        forceReplace: Boolean = false
    ) {
        this.context = context
        this.url = url
        this.forceReplace = forceReplace
        //弹窗设置
        val view =
            View.inflate(context, R.layout.dialog_update, null)
        downloadDialog = customizeDialogCenter(
            context,
            view,
            false
        )
        downloadDialog?.run {
            progressBar = findViewById<NumberProgressBar>(R.id.update_progressBar)
            updateSure = findViewById<ShadowLayout>(R.id.update_sure)
            updateCancel = findViewById<TextView>(R.id.update_cancel)
            //内容
            findViewById<TextView>(R.id.update_content).text = content
            //确定
            updateSure?.setOnClickListener(this@DownLoadViewModel)
            //取消
            updateCancel?.setOnClickListener(this@DownLoadViewModel)
            findViewById<ImageView>(R.id.update_close).setOnClickListener(this@DownLoadViewModel)
            //显示
            show()
        }

    }

    /**
     * 弹窗点击
     */
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.update_sure -> {
                progressBar?.visibility = VISIBLE
                updateSure?.isEnabled = false
                updateCancel?.isEnabled = false
                updateSure?.visibility = INVISIBLE
                updateCancel?.visibility = INVISIBLE
                download(url, "${getAppName(context!!) + dateToString()}.apk")
            }
            R.id.update_cancel, R.id.update_close -> {
                job?.cancel()
                downloadDialog?.dismiss()
                if (forceReplace) {
                    exitProcess(0)
                }
            }
            else -> {
            }
        }
    }

    /**
     * 下载
     * @param url 下载路径
     * @param fileName 文件名
     * @param isPublic 是否下载到公共目录
     */
    @OptIn(DelicateCoroutinesApi::class)
    private fun download(url: String, fileName: String, isPublic: Boolean = false) {
        val download =
            com.sdkx.wear_os.retrofit.download.download(url, object : IDownloadBuild() {
                override fun getContext() = MyApplication.application
                override fun getDownloadFile(): File? {
                    return if (isPublic) {
                        null
                    } else {
                        File(savePath(), fileName)
                    }
                }

                override fun getFileName(): String {
                    return fileName
                }

                override fun getUri(contentType: String): Uri? {
                    //下载到共享目录，这里需要考虑android10以上
                    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        val values = ContentValues().apply {
                            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) //文件名
                            put(MediaStore.MediaColumns.MIME_TYPE, contentType) //文件类型
                            put(Downloads.DATE_TAKEN, System.currentTimeMillis())
                            put(
                                MediaStore.MediaColumns.RELATIVE_PATH,
                                Environment.DIRECTORY_DOWNLOADS
                            )
                        }
                        getContext().contentResolver.insert(
                            Downloads.EXTERNAL_CONTENT_URI,
                            values
                        )
                    } else {
                        Uri.fromFile(File(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath + File.separator + fileName))
                    }
                }
            })
        //开始下载
        job = GlobalScope.launch {
            download.collect {
                when (it) {
                    is DownloadStatus.DownloadError -> {
                        //下载错误
                        logUtil("下载", "失败")
                        downloadDialog?.dismiss()
                        MainScope().launch {
                            downloadSuccessFlow?.emit(null)
                        }
                    }
                    is DownloadStatus.DownloadSuccess -> {
                        //下载成功
                        logUtil("下载", "成功${it.uri}")
                        downloadDialog?.dismiss()
                        MainScope().launch {
                            downloadSuccessFlow?.emit(it.uri)
                        }
                    }
                    is DownloadStatus.DownloadProcess -> {
                        //已下载长度 :it.currentLength
                        //文件总长度：it.length
                        //下载进度： it.process
                        MainScope().launch {
                            progressBar?.progress = floor(it.process * 100).toInt()
                        }
                    }
                    else -> {
                    }
                }
            }
        }

    }
}
